package com.qsd.common.util;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * 通用分页查询工具类
 * create by it_mck·Miao
 */
public class MyQueryPageUtil {

    /**
     * 1:创建QueryWrapper对象
     * 2:前端js请求传入,例如:like$name,eq$name ...
     * 3:对应当前条件查询支持 eq,like,likeLeft,likeRight,ge,le 默认为eq
     *
     * @param param 参数列表
     * @param <T>   泛型
     * @return
     */
    public static <T> Page<T> builder(BaseMapper<T> mapper, Map<String, Object> param) {
        Long pageSize = 10L;//每页大小
        Long currentPage = 1L;//当前页
        Set<Map.Entry<String, Object>> entries = param.entrySet();
        QueryWrapper<T> tQueryWrapper = new QueryWrapper<>();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (StringUtils.isNoneBlank(key)) {
                if (StringUtils.equals("pageSize", key)) {
                    pageSize = (Long) value;
                } else if (StringUtils.equals("currentPage", key)) {
                    currentPage = (Long) value;
                } else {
                    String[] split = key.split("\\$");
                    switch (split[0]) {
                        case "like":
                            tQueryWrapper.like(split[1], value);
                            break;
                        case "likeLeft":
                            tQueryWrapper.likeLeft(split[1], value);
                            break;
                        case "likeRight":
                            tQueryWrapper.likeRight(split[1], value);
                            break;
                        case "ge":
                            tQueryWrapper.ge(split[1], value);
                            break;
                        case "le":
                            tQueryWrapper.le(split[1], value);
                            break;
                        case "eq":
                        default:
                            tQueryWrapper.eq(split[1], value);
                            break;

                    }
                }
            }
        }
        return mapper.selectPage(new Page<>(currentPage,pageSize),tQueryWrapper);
    }

}
